import React, { Component } from 'react'
import { browserHistory } from 'react-router';
import { Modal, Button, Breadcrumb, Select , Form, Input, Radio,Col,Icon,message} from 'antd';
const Option = Select.Option;
// import Actions from '../../actions';
import {fetchData} from '../AjaxConsumer'
const confirm = Modal.confirm;
const FormItem = Form.Item;
import styles from './index.scss'
import cookie from 'react-cookie';
import { Link } from 'react-router';
import $ from 'jquery'


function itemRender(route, params, routes, paths) {
  const last = routes.indexOf(route) === routes.length - 1;
  return last ? <span>{route.breadcrumbName}</span> : <Link to={paths.join('/')}>{route.breadcrumbName}</Link>;
}


export default class TopHeader extends Component {
    constructor(props) {
        super(props);
        this.state = {
            menuCtrlImg: '',
            userName: '',
            optionData: null,
            visible: false,
        }
    }

    longOutHandle = () => {
      //itemRender('route', '', 'routes', 'main')
      console.log("你竟然点击了退出");
      confirm({
        title: '确定退出吗?',
        onOk() {
            // cookie.remove('userId', { path: '/' });
            // cookie.remove('userPwd', { path: '/' });
            $.ajax({
                url: '/base/auth/logout',
                type: 'get',
                dataType: 'json'
            }).done(function (data, status, xhr) {}.bind(this));
            browserHistory.push('/');
        },
        onCancel() {

        },
      });
    };

    showModal = () => {
        this.setState({ visible: true });
    }

    saveFormRef = (form) => {
        this.form = form;
    }

    handleCancel = () => {
        this.setState({ visible: false });
    }

    // handleRfPwdEdit = () =>{
    //     const form = this.form;
    //     form.validateFields((err, values) => {
    //         if (err) {
    //             return;
    //         }
    //         console.log('Received values of form: ', values);
    //         if(values.NewHandoverPwd==''||values.OldHandoverPwd==''||values.ConfirmHandoverPwd==''){
    //             Modal.error({
    //                 title: '提示',
    //                 content: '请输入交接密码/新交接密码/确认交接密码！',
    //             });
    //             return;
    //         }

    //         if(values.NewHandoverPwd!=values.ConfirmHandoverPwd){
    //             Modal.error({
    //                 title: '提示',
    //                 content: '新交接密码与确认交接密码不一致！',
    //             });
    //             return;
    //         }

    //         const options= {
    //             url: '/base/auth/u/pwd/rf',
    //             condition:values,
    //             // contentType:'application/json; charset=utf-8'
    //         };
                
    //         fetchData(this, options, (resData) => {
    //             console.log(resData);
    //             message.success('修改成功!')
    //             form.resetFields();
    //             this.setState({ visible: false });
    //         });
    //     })
    // }

    handleSysPwdEdit = () => {
        const form = this.form;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            console.log('Received values of form: ', values);

           if(values.NewLoginPwd==''||values.ConfirmLoginpwd==''||values.OldLoginPwd==''){
                Modal.error({
                    title: '提示',
                    content: '请输入登录密码/新登录密码/确认登录密码！',
                });
                return;
            }

            if(values.NewLoginPwd!=values.ConfirmLoginpwd){
                Modal.error({
                    title: '提示',
                    content: '新登录密码与确认登录密码不一致！',
                });
                return;
            }
  confirm({
    title: '提示',
    content: '您确定要修改密码？',
    onOk() {
       const options= {
                url: '/base/auth/u/pwd/sys',
                condition:values,
                // contentType:'application/json; charset=utf-8'
            };
                
            fetchData(this, options, (resData) => {
                console.log(resData);
                if(resData.code=='1'){
                    form.resetFields();
                    // this.setState({ visible: false });
                    Modal.success({
                        title: '修改成功!',
                        content: '即将退出系统请重新进入',
                        onOk(){
                            $.ajax({
                                url: '/base/auth/logout',
                                type: 'get',
                                dataType: 'json'
                            }).done(function (data, status, xhr) {}.bind(this));
                            browserHistory.push('/');
                        }
                    });
                }else{
                      message.error('修改失败!')
                }
          
                
            });

    },
    onCancel() {
      console.log('Cancel');
    },
  });
           
        });
    }

    checkPassword = (rule, value, callback) => {
        const form = this.form;
        if (value && value !== form.getFieldValue('NewLoginPwd')) {
            callback('两次输入登录密码不一致');
        } else {
            callback();
        }
        //  console.log('---------', form);
    }
    checkHandoverPassword = (rule, value, callback) => {
        const form = this.form;
        if (value && value !== form.getFieldValue('NewHandoverPwd')) {
            callback('两次输入交接密码不一致');
        } else {
            callback();
        }
        
    }
    checkOldHandoverPassword = (rule, value, callback) => {
        const form = this.form;
        if (form.getFieldValue('OldHandoverPwd')=="") {
            callback('请输入原交接密码');
        } else {
            callback();
        }
        console.log('---------', form.getFieldValue('OldHandoverPwd'));
    }

    
    checkNum(rule, value, callback) {
        // var re =/^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*).{8,20}$/;
        // // var re1 =/^(?=[0-9a-zA-Z@_-]+$)/;
        // var re1 =/^(?=[0-9a-zA-Z`~!@#$%^&*()_+<>?:{},.;]+$)/;

        // if (re.test(value)||value.length==0) {
        //     if (re1.test(value)||value.length==0) {
        //         callback();
        //     } else {
        //         callback('特殊符号只能为`~!@#$%^&*()_+<>?:{},.;');
        //     }         
        // } else {
        //     callback('密码必须有数字、大写及小写字母、长度为8-20位');
        // }
        if (/[\u4E00-\u9FA5]/i.test(value)) {
            callback('密码不能包含中文');
        }else{ 
            callback();
            }
    }; 
    
    //点击折叠显示效果
    handClick = () => {
        let menuCtrlImg = this.state.menuCtrlImg;
        if (menuCtrlImg == "") {
            menuCtrlImg = "lachu";
        } else {
            menuCtrlImg = "";
        }
        this.setState({
            menuCtrlImg: menuCtrlImg
        })
    };
    itemRender = (route, params, routes, paths) => {
      const last = routes.indexOf(route) === routes.length - 1;
      return last ? <span>{route.breadcrumbName}</span> : <Link to={paths.join('/')}>{route.breadcrumbName}</Link>;
    };
    //工厂选择改变的时候
    handleChange = (value) => {
        console.log(`selected factory ${value}`);
        const option= {
            url: `/base/auth/changeFactory/${value}`,
            condition:{},
            type: 'get', 
        };
        fetchData(this, option, (resData) => {
                if(resData.code == "1"){
                    this.props.refreshLeftMenu();
                    console.log(value)
                    window.localStorage.setItem('gongc',value)
                    window.location.replace(location) 
                }else{
                    console.log("请求数据错误：", resData.message);
                }
        });
        console.log(value)
    };

    //获取用户信息
    userinfo =() => {
        //无数据时候的备用信息
        const factoryOption = [
            {
                factoryCode: '123',
                factoryName: '中二工厂'
            },
            {
                factoryCode: '456',
                factoryName: 'factory2'
            },
            {
                factoryCode: '789',
                factoryName: 'factory3'
            }
        ];
        const option= {
            url: '/base/auth/userinfo',
            condition:{},
            type: 'get', 
        };
        fetchData(this,option,(res)=>{
            this.setState({
                userName: res.data.userInfo.userName,
                optionData: res.data.factories ? res.data.factories : factoryOption
            })
        })
        

    };
    componentDidMount () {
        this.userinfo();
    }

    render() {

        const CollectionCreateForm = Form.create()(
        (props) => {
            
            const { visible, onCancel, form ,onRfEdit,onSysEdit} = props;
            const { getFieldDecorator,getFieldValue } = form;

            return (
            <Modal
                width='400px'
                visible={visible}
                title="修改密码"
               onCancel={onCancel}
            /* footer={[                  
                    <Button type="primary" style={{marginRight:'150px'}} size="large" onClick={onSysEdit}>
                        修改登录密码
                    </Button>,
                    <Button type="primary" style={{marginRight:'50px'}} size="large" onClick={onRfEdit}>
                        修改交接密码
                    </Button>,
                ]} */
                footer={[<div/>]}

                
            >
            <div style={{height:'350px'}}>
                <Form layout="vertical">
                    <div>
                    <Col offset={4} span={16}>
                        <FormItem label="原密码">
                            {getFieldDecorator('OldLoginPwd', {
                                initialValue:'',
                                
                            rules: [
                                // { required: true, message: '请输入'  }
                            ],
                            })(
                            <Input  type="password" />
                            )}
                        </FormItem>
                        <FormItem label="新密码" hasFeedback>
                            {getFieldDecorator('NewLoginPwd', {
                                initialValue:'',
                                rules: [
                                    // { required: true, message: '请输入' }
                                    {validator: this.checkNum}
                                ],
                                
                            })(
                            <Input type="password"  />
                            )}               
                        </FormItem>
                        <FormItem label="确认密码" hasFeedback>
                            {getFieldDecorator('ConfirmLoginpwd', {
                            initialValue:'',
                                rules: [
                                    // { required: true, message: '请输入' },
                                    {validator: this.checkPassword,}
                                ],
                            })(
                            <Input type="password" />
                            )}
                        </FormItem>
                        </Col>
                       
                        </div>
                  
                    <div style={{height:'150px'}} >
                    <row >
                    <Col offset={10} span={7}>
                    
                    <Button type="primary" style={{marginRight:'50px'}} size="large" onClick={onSysEdit}>
                    <Icon type="edit"/>修改
                    </Button>
                    </Col>
                    </row>
                    </div>
                   
                </Form>
            </div>
            </Modal>
            );
                
        }
        
        );


        let userName = this.state.userName ? this.state.userName : '闯入者';
        let optionData = this.state.optionData ? this.state.optionData : null;
        let factorySelect;
        let defaultFactory;
        if ( optionData == null || typeof(optionData) == undefined) {
            factorySelect = '';
        } else {
            if(window.localStorage.getItem("gongc")==null||window.localStorage.getItem("gongc")==""){
                defaultFactory=optionData[0].factoryCode;
            }else{
                for(var i in optionData){
                    if(optionData[i].factoryCode==window.localStorage.getItem("gongc")){
                    defaultFactory=window.localStorage.getItem("gongc")
                    break;
                    }else{
                        defaultFactory=optionData[0].factoryCode;
                    }
            }
            }
            factorySelect = <Select
                                size="small"
                                showSearch
                                style={{textAlign:'center', marginLeft:'40px', width:'200px',  marginTop:'15px',borderRadius:'10px',float:'left' }}
                                placeholder="Select a factory"
                                optionFilterProp="children"
                                onChange={this.handleChange}
                                defaultValue={defaultFactory}
                                filterOption={(input, option) => option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                >
                                {
                                  optionData.map((e,index)=>{
                                    return(<Option key={index} value={e.factoryCode}>{e.factoryName}</Option>)
                                  })
                                }
                            </Select>
        }
        return (
            <div className="top">
                <i className={"shouqi " + this.state.menuCtrlImg} onClick={this.props.hck}> </i>
                <Breadcrumb itemRender={itemRender} />
                {factorySelect}
                <div className={styles.topRight}>
                    {/* <a className={styles.notice}><span className={styles.noticeNumber}>3</span></a> */}
                    <i className={styles.splitSolid}></i>
                    <a className="changeStyle" style={{marginRight: '10px'}}></a>                  
                    <span style={{fontSize: '12px', color: '#fff', cursor: 'pointer'}}>{userName}</span>

                    <span className={styles.configConfirm}>
                        <a href="javascript: void(0);" className={styles.config}><i className={styles.arrow}></i></a>
                        <ul className={styles.downContent}>
                            <li>
                                <Icon type="key"/>
                                <a href="javascript: void(0);" onClick={this.showModal}>修改密码</a>
                                     
                            </li>
                            <li>
                                <Icon type="poweroff"/>
                                <a href="javascript: void(0);" onClick={this.longOutHandle}>退出</a>
                            </li>
                            <li>
                                <CollectionCreateForm
                                        ref={this.saveFormRef}
                                        visible={this.state.visible}
                                        onCancel={this.handleCancel}
                                        onRfEdit={this.handleRfPwdEdit}
                                        onSysEdit={this.handleSysPwdEdit}
                                    />
                            </li>
                        </ul>
                    </span>

                </div><div className={styles.esp}>
                    {/*<a className={styles.p} target="_blank" href="http://10.10.45.33:8081/imes-web/chooseProgram"><Icon type="question-circle-o" /> 选择系统</a>*/}
                    {/* <a className={styles.p} href="http://47.105.106.224:8081/imes-web/chooseProgram"><Icon type="appstore-o" /> 选择系统</a> */}
                </div>
            </div>
        );
    }
}
